package zcatt.ex006.ui.preferencestore;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.ui.preferences.ScopedPreferenceStore;
import org.osgi.service.prefs.Preferences;

public class MyPreferenceView extends ViewPart {
	Text text;
	List<Preferences> eps;

	public MyPreferenceView() {
		// TODO Auto-generated constructor stub
	}

	void logPreferences(Preferences p)
	{
		if(eps.contains(p))
			return;
		
		eps.add(p);
		
		text.append("\n#" + eps.size() + ", Preference= " 
					+ (!p.name().isEmpty() ? p.name() : "(root)") 
					+ ", parent=" 
					+ (p.parent() == null ? "(null)" :(p.parent().name().isEmpty() ? "(root)" : p.parent().name()))
					+ ", path="+p.absolutePath()
					+ "   .............................\n");
		
		try {
			String[] keys = p.keys();
			for(String key : keys)
			{
				String value = p.get(key, "(noname)");
				text.append("    " + key + ", " + value +"\n");					
			}				
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}		
		
		Preferences parent = p.parent();
		if(parent != null)
			logPreferences(parent);
	}
	
	@Override
	public void createPartControl(Composite parent) {
		text = new Text(parent, SWT.BORDER|SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL);
		text.setText("zcatt.ex004.ui.view\n");
		
		ScopedPreferenceStore scopePrefStore = (ScopedPreferenceStore) Activator.getDefault().getPreferenceStore();		
		IEclipsePreferences[] epArray = scopePrefStore.getPreferenceNodes(true);		
		
		eps = new ArrayList<Preferences>(10);

		for(int i = 0; i< epArray.length; i++)
		{
			logPreferences(epArray[i]);
		}
	}

	@Override
	public void setFocus() {
		text.setFocus();

	}

}
